<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能财务管理系统</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
</head>
<body class="bg-light">
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="#"><i class="fas fa-coins mr-2"></i>财务管理系统</a>
        <div class="ml-auto">
            <button id="logoutBtn" class="btn btn-outline-light">登出</button>
        </div>
    </nav>

    <div class="container py-5">
        <!-- 数据概览 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card shadow">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-wallet text-success"></i> 总收入</h5>
                        <h3 id="totalIncome">￥0.00</h3>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card shadow">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fas fa-shopping-cart text-danger"></i> 总支出</h5>
                        <h3 id="totalExpense">￥0.00</h3>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作区 -->
        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="card shadow">
                    <div class="card-body">
                        <h4 class="mb-4"><i class="fas fa-plus-circle"></i> 新增记录</h4>
                        <ul class="nav nav-tabs" id="recordTab">
                            <li class="nav-item">
                                <a class="nav-link active" data-toggle="tab" href="#income">收入</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" data-toggle="tab" href="#expense">支出</a>
                            </li>
                        </ul>
                        
                        <div class="tab-content mt-3">
                            <!-- 收入表单 -->
                            <div class="tab-pane fade show active" id="income">
                                <form id="incomeForm">
                                    <input type="number" id="incomeAmount" placeholder="金额" class="form-control mb-2">
                                    <input type="date" id="incomeDate" class="form-control mb-2">
                                    <input type="text" id="incomeCategory" placeholder="分类" class="form-control mb-2">
                                    <input type="text" id="incomeDescription" placeholder="描述" class="form-control mb-2">
                                    <button type="submit" class="btn btn-success btn-block">添加收入</button>
                                </form>
                            </div>
                            
                            <!-- 支出表单 -->
                            <div class="tab-pane fade" id="expense">
                                <form id="expenseForm">
                                    <input type="number" id="expenseAmount" placeholder="金额" class="form-control mb-2">
                                    <input type="date" id="expenseDate" class="form-control mb-2">
                                    <input type="text" id="expenseCategory" placeholder="分类" class="form-control mb-2">
                                    <input type="text" id="expenseDescription" placeholder="描述" class="form-control mb-2">
                                    <button type="submit" class="btn btn-danger btn-block">添加支出</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 数据表格 -->
            <div class="col-md-6">
                <div class="card shadow">
                    <div class="card-body">
                        <h4 class="mb-4"><i class="fas fa-history"></i> 交易记录</h4>
                        <table class="table table-hover">
                            <thead class="thead-light">
                                <tr>
                                    <th>类型</th>
                                    <th>金额</th>
                                    <th>日期</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="recordsTable">
                                <!-- 动态加载数据 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            // 初始化认证检查
            if(!localStorage.getItem('authToken')) {
                window.location.href = '/login/';
            }

            // 通用提交处理
            function handleFormSubmit(formId, url) {
                $(formId).submit(function(e) {
                    e.preventDefault();
                    const formData = Object.fromEntries(new FormData(this));
                    
                    $.ajax({
                        url: url,
                        type: 'POST',
                        headers: {
                            'Authorization': 'Token ' + localStorage.getItem('authToken')
                        },
                        data: formData,
                        success: function() {
                            alert('操作成功！');
                            $(formId)[0].reset();
                            loadFinancialData();
                        },
                        error: function(xhr) {
                            alert(`错误：${xhr.responseJSON?.detail || '未知错误'}`);
                        }
                    });
                });
            }

            // 绑定表单
            handleFormSubmit('#incomeForm', '/api/incomes/');
            handleFormSubmit('#expenseForm', '/api/expenses/');

            // 加载数据
            function loadFinancialData() {
                $.ajax({
                    url: '/api/summary/',
                    headers: {
                        'Authorization': 'Token ' + localStorage.getItem('authToken')
                    },
                    success: function(data) {
                        // 更新数据
                        $('#totalIncome').text(`￥${data.total_income}`);
                        $('#totalExpense').text(`￥${data.total_expense}`);
                        updateRecordsTable(data.latest_records);
                    },
                    error: function(xhr) {
                        console.error('API请求失败:', xhr.statusText);  // 新增错误日志
                        alert('无法加载财务数据，请检查网络连接');
                    }
                });
            }

            // 新增记录表格更新函数
            function updateRecordsTable(records) {
                const tbody = $('#recordsTable').empty();
                
                records.forEach(record => {
                    const row = $('<tr>').append(
                        $('<td>').text(record.type).css('color', record.type === '收入' ? 'green' : 'red'),
                        $('<td>').text('￥' + record.amount),
                        $('<td>').text(record.date),
                        $('<td>').append(
                            $('<button>').addClass('btn btn-sm btn-danger')
                                .html('<i class="fas fa-trash"></i>')
                                .click(() => deleteRecord(record.id))
                        )
                    );
                    tbody.append(row);
                });
            }

            // 新增删除记录功能
            function deleteRecord(recordId) {
                if (confirm('确定要删除这条记录吗？')) {
                    $.ajax({
                        url: `/api/records/${recordId}/`,
                        type: 'DELETE',
                        headers: {
                            'Authorization': 'Token ' + localStorage.getItem('authToken')
                        },
                        success: () => {
                            loadFinancialData();
                            alert('删除成功');
                        },
                        error: (xhr) => {
                            alert(`删除失败：${xhr.statusText}`);
                        }
                    });
                }
            }
            // 初始化加载
            loadFinancialData();
        });
    </script>
</body>
</html>